import httplib
import xmlrpclib

def T(l,transport):
	return xmlrpclib.ServerProxy(l,transport=transport)
	
class xx(xmlrpclib.Transport):
	"""Handles an HTTP transaction to an XML-RPC server."""
	
	# client identifier (may be overridden)
	#~ user_agent = "xmlrpclib.py/%s (by www.pythonware.com)" % __version__
	
	def make_connection(self, host):
		# create a HTTP 1.1 connection object from a host descriptor
		# we want to reuse the same socket over and over
		R=httplib.HTTPConnection(host)
		return R
	
	def getreply(self, httpresp):
		"""Compat definition since superclass does not define it.
		
		Returns a tuple consisting of:
		- server status code (e.g. '200' if all goes well)
		- server "reason" corresponding to status code
		- any RFC822 headers in the response from the server
		"""
		try:
			response = httpresp.getresponse()
		except httplib.BadStatusLine, e:
			### hmm. if getresponse() ever closes the socket on a bad request,
			### then we are going to have problems with self.sock
	
			### should we keep this behavior? do people use it?
			# keep the socket open (as a file), and return it
			httpresp.file = httpresp._conn.sock.makefile('rb', 0)
	
			# close our socket -- we want to restart after any protocol error
			httpresp.close()
	
			httpresp.headers = None
			return -1, e.line, None
	
		httpresp.headers = response.msg
		httpresp.file = response.fp
		return response.status, response.reason, response.msg

	def xparse_response(self, f):
		# read response from input file, and parse it
		
		p, u = self.getparser()
		
		while 1:
			response = f.read(1024)
			if not response:
				break
			if self.verbose:
				print "body:", repr(response)
			p.feed(response)
		
		f.close()
		p.close()
		
		return u.close()

	def request(self, host, handler, request_body, verbose=0):
		# issue XML-RPC request
		
		try:
			h=self._h
		except AttributeError:
			h = self.make_connection(host)
			self._h =h
			if verbose:
				print '** new connection'
				h.set_debuglevel(1)
		
		self.send_request(h, handler, request_body)
		self.send_host(h, host)
		self.send_user_agent(h)
		self.send_content(h, request_body)
		
		errcode, errmsg, headers = self.getreply(h)
		
		#~ print 900,errcode, errmsg, headers, request_body
		
		if errcode != 200:
			raise xmlrpclib.ProtocolError(
				host + handler,
				errcode, errmsg,
				headers
				)
		
		self.verbose = verbose
		
		return self.parse_response(h.file)#getfile())

#
# eof
#
